package com.hxg.common.dao.impl;

import com.hxg.common.dao.BlVerfiyDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Repository("blVerfiyDao")
public class BlVerfiyDaoImpl implements BlVerfiyDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
        return new NamedParameterJdbcTemplate(this.jdbcTemplate);
    }

    @Override
    public boolean repeat(String value, String tableName, String col, String primaryKey, String primaryKeyValue) {
        Map<String, Object> paramMap = new HashMap<>();

        paramMap.put("value", value);
        String querySQL = "select count(1) from " + tableName + " where " + col + " = :value";
        if (StringUtils.isNotEmpty(primaryKeyValue)) {
            paramMap.put("primaryKeyValue", primaryKeyValue);
            querySQL += " and " + primaryKey + " != :primaryKeyValue";
        }

        log.info("repeat:\n{}\n参数: {}", querySQL, paramMap);
        Integer count = this.getNamedParameterJdbcTemplate().queryForObject(querySQL, paramMap, Integer.class);
        return count > 0;
    }

    @Override
    public boolean repeatAppId(String appId, String value, String tableName, String col, String primaryKey,
                               String primaryKeyValue) {
        Map<String, Object> paramMap = new HashMap<>();

        paramMap.put("value", value);
        String querySQL = "select count(1) from " + tableName + " where app_id = :appId and " + col + " = :value";
        if (StringUtils.isNotEmpty(primaryKeyValue)) {
            paramMap.put("primaryKeyValue", primaryKeyValue);
            querySQL += " and " + primaryKey + " != :primaryKeyValue";
        }
        paramMap.put("appId", appId);

        log.info("repeatAppId:\n{}\n参数: {}", querySQL, paramMap);
        Integer count = this.getNamedParameterJdbcTemplate().queryForObject(querySQL, paramMap, Integer.class);
        return count > 0;
    }
}
